package com.news.news.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.news.news.dao.AdminDao;
import com.news.news.dao.LoginDao;
import com.news.news.modle.Admin;
import com.news.news.modle.Menu;
import com.news.news.modle.Role;
import com.news.news.util.JWTUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 罗铠威 on 2023/8/29 16:21
 * type:
 */
@Service
@Transactional
public class AdminService {

    @Resource
    AdminDao adminDao;

    public PageInfo<Admin> adminList(Admin admin){
        PageHelper.startPage(admin.getPageNum(),admin.getPageSize());
        ArrayList<Admin> admins = adminDao.adminList(admin);
        PageInfo<Admin> pageInfo = new PageInfo<>(admins);
        return pageInfo;
    }

    public List<Role>  findRoles(){
      return   adminDao.finRoles();
    }

    public void saveAdmin(Admin admin) {
        //设置密码
        String password = DigestUtils.md5DigestAsHex("123".getBytes());
        admin.setPassword(password);
        //获取操作人
        admin.setOperAdmin(JWTUtil.getOperIdByToken(admin.getAdminToken()));
        //保存admin信息并返回id
        adminDao.saveAdmin(admin);
        //保存admin与角色的关系
        if(admin.getRoles().length!=0){
            for (Integer role : admin.getRoles()) {
                adminDao.addAdminRole(role,admin.getId());
            }
        }

    }

    public Admin findAdminById(Integer id) {
       Admin admin=adminDao.findAdminById(id);
       Integer[] a=new Integer[admin.getRole().size()];
        for (int i = 0; i <a.length ; i++) {
            a[i]=admin.getRole().get(i).getId();
        }
        admin.setRoles(a);
       return admin;
    }

    public void updateAdmin(Admin admin) {
        //获取操作人
        admin.setOperAdmin(JWTUtil.getOperIdByToken(admin.getAdminToken()));
        //保存admin表信息通过ID
        adminDao.updateAdmin(admin);
        //保存管理员与角色·之间的关系(先删除再添加)
        adminDao.deleteAdminRole(admin.getId());
        if(admin.getRoles().length!=0){
            for (Integer role : admin.getRoles()) {
                adminDao.updateAdminRole(role,admin.getId());
            }
        }

    }

    public void deleteAdmin(Integer adminid) {
        adminDao.deleteAdminRole(adminid);
        adminDao.deleteAdmin(adminid);
    }

    public ArrayList<Menu> showMenu(String adminToken) {
        ArrayList<Menu> menus=null;
        Integer id = JWTUtil.getTokenInfo(adminToken).getClaim("id").asInt();
        Integer type = JWTUtil.getTokenInfo(adminToken).getClaim("type").asInt();
        menus= adminDao.showMenu(id,type);
        return menus;
    }
}
